import { Component, OnInit } from '@angular/core';
import {NoticeService} from '../notice.service';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService } from 'primeng/primeng';
import {switchMap} from 'rxjs/operators';

@Component({
  selector: 'app-notice-edit',
  templateUrl: './notice-edit.component.html',
  styleUrls: ['./notice-edit.component.scss'],
  providers: [NoticeService]
})
export class NoticeEditComponent implements OnInit {
    roleTypes: any[] = []; // 收件人角色集
    roleList: any[] = []; // 收件人
    title: string; // 标题
    publishUnit: string; // 发布单位
    grade: number = 1; // 等级
    content: string = ""; // 内容
    noticeDocFileList: any[] = [];
    attachmentIds: any[] = []; // 附件标识
    attachmentNames: any[] = []; // 附件名称
    isSendComplete: boolean = false; // 发送是否完成，来控制关闭按钮是否
    titleErrors: boolean = false;
    publishUnitErrors: boolean = false;
    roleListErrors: boolean = false;
    errorMessage: String;
    noticeId: any;

  constructor(
      private router: Router,
      private route: ActivatedRoute,
      private noticeService: NoticeService,
      private mdlSnackbarService: MdlSnackbarService,
      private confirmationService: ConfirmationService) { }

  ngOnInit() {
        // 获取发送公告角色
      this.noticeService.loadRoleData().subscribe(roles => {
          this.roleTypes = roles;
      });

      this.route.paramMap.pipe(
          switchMap((params: ParamMap) => {
              this.noticeId = +params.get('noticeId') || 0;
              return this.noticeService.loadNoticeById(this.noticeId);
          })
      ).subscribe(data => {
          if (data) {
              this.title = data.title;
              this.publishUnit = data.publishUnit;
              this.grade = data.grade;
              this.content = data.content;
              this.roleList = data.roles;
              this.attachmentIds = data.attachmentIds == null ? [] : data.attachmentIds.split('/');
              this.attachmentNames = data.attachmentNames == null ? [] : data.attachmentNames.split('/');
              this.noticeDocFileList = data.urls == null ? [] : data.urls;
          }
      });
  }

  send() {
      this.isSendComplete = true;
      if (this.title == null || this.title == '' || this.title == undefined) {
          this.titleErrors = true;
          this.errorMessage = '标题不能为空';
          this.isSendComplete = false;
          return;
      }
      if (this.publishUnit == null || this.publishUnit == '' || this.publishUnit == undefined) {
          this.publishUnitErrors = true;
          this.errorMessage = '发布不能为空';
          this.isSendComplete = false;
          return;
      }
      if (this.roleList == null  || this.roleList == undefined) {
          this.roleListErrors = true;
          this.errorMessage = '收件人不能为空';
          this.isSendComplete = false;
          return;
      }
      let params = {};
      if (this.noticeId > 0) {
          params['noticeId'] = this.noticeId;
      }
      params['title'] = this.title;
      params['publishUnit'] = this.publishUnit;
      params['grade'] = this.grade;
      params['content'] = this.content;
      params['attachmentIds'] = this.attachmentIds.join('/');
      params['attachmentNames'] = this.attachmentNames.join('/');
      params['roles'] = this.roleList;
      this.noticeService.save(params).subscribe( data => {
          if (data) {
              this.mdlSnackbarService.showToast('信息发布成功！');
              this.reject();
          } else {
              this.mdlSnackbarService.showToast('信息发布失败！');
          }
      });
  }

  // 关闭
  close() {
      this.confirmationService.confirm({
          header: '确认',
          message: '是否需要发送该条公告？',
          accept: () => {
              this.send();
          }
      });
  }

  reject() {
      this.router.navigate(['/notification/publishlist']);
  }

    cleanMessage() {
        this.titleErrors = false;
        this.publishUnitErrors = false;
        this.roleListErrors = false;
    }

    /**文件上传地址 */
    onFileUpload() {
        let url = location.origin + '/media/api/upload';
        return url;
    }

    /** 文件发生变化时的列表 */
    noticeDocChange(info) {
        const fileList = info.fileList;
        if (info.file.response) {
            info.file.url = info.file.response.url;
        }
        if (info.type === 'success') {
            const data = info.file.response.data;
            this.attachmentIds.push(data.mediaId);
            this.attachmentNames.push(data.mediaName);
        }
        if (info.type === 'removed') {
            this.attachmentIds = [];
            this.attachmentNames = [];
            if (fileList.length > 0) {
                fileList.filter((item: any) => {
                    if (item.response) {
                        const  data = item.response.data;
                        this.attachmentIds.push(data.mediaId);
                        this.attachmentNames.push(data.mediaName);
                    } else {
                        this.attachmentIds.push(item.uid);
                        this.attachmentNames.push(item.name);
                    }
                });
            }
        }
        this.noticeDocFileList = fileList.filter((item: any) => {
            if (item.response) {
                return item.response.code = '0';
            }
            return true;
        });
    }
}
